import type { MenuItem } from "@/types/user";
import type { AppRouteRecordRaw } from "./types";
import { componentMap } from "./types";
import Layout from "../layout/index.vue";
const modules = import.meta.glob("@/views/**/index.vue");
function loadView(url: string) {
  console.log(modules[`@/views/dashboard/index.vue`]);
  
  return modules[`@/views/${url}/index.vue`];
}

// 处理组件路径
function handleComponent(component: string) {
  if (component === "Layout") {
    return componentMap["Layout"];
  }
  return (
    componentMap[component] || (() => import(`@/views/${component}/index.vue`))
  );
}

// 生成路由配置
export function generateRoutes(menuList: MenuItem[]): AppRouteRecordRaw[] {
  const routes: AppRouteRecordRaw[] = [];

  menuList.forEach((menu) => {
    if (menu.parentId === "0" && menu.isShow === "0") {
      console.log("menu:", menu);

      const route: AppRouteRecordRaw = {
        path: menu.resComponent || menu.resUrl,
        name: menu.resCode,
        component: () => import("@/layout/index.vue"),
        meta: {
          title: menu.resName,
          icon: menu.resIcon,
        },
        children: [],
      };

      // 查找子菜单
      const children =
        menu.children?.filter((item) => {
          console.log("item:", item);
          // item.parentId === menu.id &&
          return (
            item.parentId === menu.id &&
            item.isShow === "0" &&
            item.resType === "1"
          );
        }) || [];

      console.log("children:", children);
      if (children.length) {
        route.children = children.map((child) => {
          const url = "system/dict";
          return {
            path: child.resComponent
              .toLowerCase()
              .replace("_", "-")
              .replace("/", ""),
            name: child.resCode,
            // component: loadView(child.resComponent.replace("/", "")),
            component: () => import("@/views/system/dict/index.vue"),
            // component: () => import(`@/views/${url}/index.vue`),
            meta: {
              title: child.resName,
              icon: child.resIcon,
              permissions: [child.resPermissions],
            },
          };
        });
      }

      // 如果有子路由，添加重定向
      if (route.children?.length) {
        // route.redirect = `${route.path}/${route.children[0].path}`;
      }

      console.log("Generated route:", route);
      routes.push(route);
    }
  });

  console.log("Generated Routes:", routes);
  return routes;
}
